package com.iretailer.report.util;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.iretailer.report.model.Config;
import com.iretailer.report.model.User;
import com.iretailer.report.service.ConfigService;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;

import javax.servlet.http.HttpServletRequest;

/**
 * @program: report
 * @description:
 * @author: Bennie
 * @create: 2020-06-22 13:33
 **/


public class SecurityUserUtil {

    public static User currentUser(HttpServletRequest request) {
        Subject subject = SecurityUtils.getSubject();
        User user = (User) subject.getPrincipal();
        User sessionUser = (User)  request.getSession().getAttribute("user");
        return user == null ? sessionUser : user;
    }

    public static String currentUserName(HttpServletRequest request) {
        User user = currentUser(request);
        if (user == null) return null;
        return user.getName();
    }


    public static String userLanguage(HttpServletRequest request) {
        User user = currentUser(request);
        if (user == null || StringUtils.isBlank(user.getLanguage())) {
            return defaultLanguage();
        }
        return user.getLanguage();
    }

    public static String defaultLanguage() {
        ConfigService cs = SpringUtils.getBean(ConfigService.class);
        Config cf = cs.getOne(new QueryWrapper<Config>().lambda().eq(Config::getConfigKey, "default_language"));
        return (cf == null || StringUtil.empty(cf.getConfigValue())) ? "en" : cf.getConfigValue();
    }
}
